#!/usr/bin/python
# -*- coding: utf-8 -*-
# Created on 2017-02-13 下午3:53
# @auther: chenyongbing
# @file: signals.py

import os, logging

log = logging.getLogger(__name__)

from django.db.models.signals import post_save
from django.db.models.signals import post_delete
from django.dispatch import receiver
from .models import  WechatVerify
from django.conf import settings
import subprocess

@receiver(post_save, sender=WechatVerify)
def model_post_save(sender, **kwargs):
    datas = kwargs['instance'].__dict__
    name  = datas.get('file',None)

    website = kwargs['instance'].host.website
    ansible_group = kwargs['instance'].host.ansible_group
    dest = kwargs['instance'].host.dest

    vfile = os.path.join(settings.MEDIA_ROOT,name)
    if os.path.exists(vfile):
        # cmd = 'ansible {group} -m copy -a "src={src} dest={dest}"'.format(group=ansible_group,src=vfile,dest=dest)
        std_out = subprocess.check_output(['ansible',ansible_group,'-m','copy','-a',"src={src} dest={dest}".format(src=vfile,dest=dest)])
        print(std_out)
    # if name!=None:
    #     commands.getstatus('ansible ')

@receiver(post_delete, sender=WechatVerify)
def model_post_delete(sender , **kwargs):
    data = kwargs['instance']

    storage, path = data.file.storage, data.file.path
    storage.delete(path)
